import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from multiprocessing import Process
import os


def create_msg(my_sender, my_pass, my_users, sender_name, user_name, yourSubject, yourText, attachments):
    msg = MIMEMultipart()
    msg['From'] = formataddr([sender_name, my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    for user in my_users:
        msg['To'] = formataddr([user_name, user])              # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msg['Subject'] = yourSubject                # 邮件的主题，也可以说是标题
    msg.attach(MIMEText(yourText, 'plain', 'utf-8'))
    for attachment in attachments:
        try:
            file = MIMEApplication(open(attachment, 'rb').read())
            file.add_header('Content-Disposition', 'attachment', filename=attachment)
            msg.attach(file)
        except OSError:
            print("%s 不存在！请输入正确路径！" % attachment)

    
    print("邮件生成完毕，准备发送，请稍等...")
    return msg

def sendtoWang(my_sender, my_user, my_pass, msg, smtpIP):
    server = smtplib.SMTP_SSL(smtpIP, 465)  # 发件人邮箱中的SMTP服务器，端口是25
    try:
        server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
    except:
        print("密码或用户名错误！请查看密码是否使用授权码！如没有，请先生成授权码！")
        os._exit(0)
    try:
    	server.sendmail(my_sender, my_user, msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    	print('发送给 %s 成功！' % my_user)
    except Exception as e:
    	print("发送给 %s 失败！" % my_user, e)
    server.quit()  # 关闭连接


if __name__ == '__main__':
    stmpInfo = input("您的邮箱是哪种？（请填写qq或者网易）:")
    if stmpInfo == "qq":
        smtpIP = "smtp.qq.com"
    else:
        smtpIP = "smtp.163.com"
    my_sender = input("请输入你的邮箱号码：")  
    my_pass = input("请输入密码：")              # 发件人邮箱密码
    my_users = input("请输入你想要发送的邮箱号(以空格分隔)：")
    my_users = my_users.split(' ')
    if type(my_users) is not list:
        print("请按规定格式输入！")
        os._exit(0)
    sender_name = input("请输入你的署名：")
    user_name = input("请输入接受者的署名：") 
    yourSubject = input("请输入邮件标题：")
    yourText = input("请输入邮件内容：")
    attachments = input("请输入你要传送的附件的目录(以空格分隔)：")
    attachments = attachments.split(' ')
    if type(attachments) is not list:
        print("请按规定格式输入！")
        os._exit(0)
    print("正在生成邮件，请稍等...")
    msg = create_msg(my_sender, my_pass, my_users, sender_name, user_name, yourSubject, yourText, attachments)
    plst = []  
    for my_user in my_users:
        p = Process(target=sendtoWang, args=(my_sender, my_user, my_pass, msg, smtpIP))
        p.start()
        plst.append(p)

    for i in plst:      		
        i.join()




